import { useEffect, useState } from 'react'
import { Table, Button, message, Space, Image, Tag, Modal, Descriptions, Badge, Radio } from 'antd'

import styles from './style.module.scss'
import { AdminService } from '../../services'
import Link from 'next/link'
import { IUser } from '../../models/types'
import { nowDay } from '../../libs/utils'
import Search from 'antd/lib/input/Search'
import { Identity } from '../../models/enums'

const { Column } = Table

const pageSize = 10

export default function User() {

  const [users, setUsers] = useState<IUser[]>([])
  const [user, setUser] = useState<IUser>()
  const [text, setText] = useState('')

  const [total, setToal] = useState<number>(0)
  const [pageIndex, setPageIndex] = useState<number>(1)

  const [visible, setVisible] = useState(false)

  const [role, setRole] = useState<Identity>(Identity.Student)
  const [modal, setModal] = useState<boolean>(false)
  const [userId, setUserId] = useState('')

  async function onOK() {
    const res = await AdminService.dealuser(userId, role)
    if (res.stat === 'OK') {
      message.success('审核成功')
      getdata(pageIndex - 1)
      onCancel()
    } else {
      message.error(res.msg)
    }
  }

  function onCancel() {
    setModal(false)
    setUserId('')
  }

  async function getdata(skip: number) {
    const res = await AdminService.userlist(skip, pageSize)
    if (res.stat === 'OK') {
      setUsers(res.data.list)
      setToal(res.data.total)
    } else {
      message.error(res.msg)
    }
  }

  async function goSearch(skip: number) {
    const res = await AdminService.userlist(skip, pageSize, text)
    if (res.stat === 'OK') {
      setUsers(res.data.list)
      setToal(res.data.total)
    } else {
      message.error(res.msg)
    }
  }

  useEffect(() => {
    getdata(0)
  }, [])

  return (
    <div className={styles.wrap}>
      <div className={styles.search} >
        <Search
          placeholder="搜索用户"
          allowClear
          enterButton="搜索"
          size="large"
          value={text}
          onChange={v => setText(v.target.value)}
          onSearch={async () => goSearch(0)}
          onPressEnter={async () => goSearch(0)}
        />
        <Button onClick={() => {
          setText('')
          getdata(0)
        }} size='large'>重置</Button>
      </div>
      <Table
        dataSource={users}
        rowKey="_id"
        pagination={{
          pageSize: pageSize,
          current: pageIndex,
          total: total,
          showSizeChanger: false,
          onChange: async (v) => {
            setPageIndex(v)
            if (text === '') getdata((v - 1) * 10)
            else goSearch((v - 1) * 10)
          }
        }}
      >
        <Column title="头像" dataIndex="avatar" key="_id"
          width={60}
          render={(avatar: string) => <Image alt='' width={50} src={avatar} />}
        />
        <Column title="账号" dataIndex="username" key="_id" />
        <Column title="昵称" dataIndex="nickname" key="_id" />
        <Column title="民大币" dataIndex="mdb" key="_id"
          render={v => <>￥{v}</>}
        />
        <Column title="身份" dataIndex="role" key="_id"
          render={v => {
            if (v === 2) return <Tag color='blue'>官方</Tag>
            return v === 3 ? <Tag color="success">学生</Tag> : <Tag color='orange'>管理员</Tag>
          }}
        />
        <Column title="账户状态" dataIndex="role" key="_id"
          render={v => <Tag color={'blue'}>正常</Tag>}
        />
        <Column
          title="操作"
          key="_id"
          render={(text, record: IUser) => {
            return (
              <Space>
                <Button
                  onClick={() => {
                    setUser(record)
                    setVisible(true)
                  }}
                  size="small"
                  type="primary"
                >
                  查看
                </Button>
                <Button
                  onClick={() => {
                    setUserId(record._id)
                    setRole(record.role)
                    setModal(true)
                  }}
                  size='small'
                  type='default'
                >编辑</Button>
              </Space>
            )
          }}
        />
      </Table>
      <Modal
        onCancel={() => setVisible(false)}
        title="用户信息" visible={visible} footer={null} width={800} >
        <Descriptions bordered>
          <Descriptions.Item label="头像"><Image alt='' width={100} src={user?.avatar} /></Descriptions.Item>
          <Descriptions.Item label="用户名:">{user?.nickname}</Descriptions.Item>
          <Descriptions.Item label="民大币">￥{user?.mdb.toFixed(2)}</Descriptions.Item>
          <Descriptions.Item label="身份">{
            user?.role === 1 && <Tag color='orange'>管理员</Tag>}
            {user?.role === 2 && <Tag color='blue'>官方</Tag>}
            {user?.role === 3 && <Tag color="success">学生</Tag>}
          </Descriptions.Item>
          <Descriptions.Item label="注册时间">
            {nowDay(user?.registerTime as number)}
          </Descriptions.Item>
          <Descriptions.Item label="联系方式">
            {user?.qqnumber}
          </Descriptions.Item>
          <Descriptions.Item label="专业" span={3}>
            <Badge status="processing" text={user?.major} />
          </Descriptions.Item>
          <Descriptions.Item label="签名" span={3}>{user?.signature}</Descriptions.Item>
        </Descriptions>
      </Modal>
      <Modal
        title="用户权限修改"
        visible={modal}
        onOk={onOK}
        onCancel={onCancel}
        okText="修改"
        cancelText='取消'
      >
        <div className={styles.audit}>
          <span className={styles.label}>权限：</span>
          <Radio.Group
            options={[
              { value: Identity.Admin, label: '管理员' },
              { value: Identity.Official, label: '官方' },
              { value: Identity.Student, label: '学生' }
            ]}
            onChange={e => setRole(e.target.value)}
            value={role}
            optionType="button"
          />
        </div>
      </Modal>
    </div>
  )
}
